package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Description:
 * Date: 2024-03-16
 */
public class UdpEchoServer2 {
    private DatagramSocket socket = null;
    public UdpEchoServer2(int port) throws SocketException {
        //手动指定端口号
        socket = new DatagramSocket(port);
        //socket = new DatagramSocket(); //这样写就是让系统自动分配端口
    }
    public void start() throws IOException { //通过这个方法来启动服务器
        System.out.println("服务器启动");
        while (true) {
            //1.读取请求并解析
            DatagramPacket requestPacket = new DatagramPacket(new byte[4060], 4060);
            socket.receive(requestPacket);
            String request = new String(requestPacket.getData(),0, requestPacket.getLength());
            String response = process(request);
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),
                    response.getBytes().length,requestPacket.getSocketAddress());
            socket.send(responsePacket);
            System.out.printf("[%s:%d] rep = %s, resp = %s\n",requestPacket.getAddress().toString()
            ,requestPacket.getPort(),request,response);
        }

    }
    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer2 server2 = new UdpEchoServer2(9090);
        server2.start();
    }
}
